﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO; 
using System.Collections;
using System.Windows.Forms;
using System.Web.UI;
using System.Net;


namespace Typo3ImageUpload
{
    public partial class Form1 : Form
    {
        private ArrayList upImages = new ArrayList();
        private System.Windows.Forms.ImageList fileFolder;

        private String actFile = null;

        public Form1()
        {
            InitializeComponent();
            progressBar.Visible = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "Bilddateien|*.jpg;*.png;*.gif";
            openFileDialog1.Title = "Select the Image Files";

            fileFolder = new ImageList(new System.ComponentModel.Container());

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
                //MessageBox.Show(sr.ReadToEnd());
                //sr.Close();
                String[] images = openFileDialog1.FileNames;
                //int newW = 0;
                // int newH = 0;
                // Size newS;
                listView1.View = View.SmallIcon;
                listView1.SmallImageList = fileFolder;
                listView1.LargeImageList = fileFolder;
                listView1.StateImageList = fileFolder;
                //Control ctrl_imglist = listView1.GetChildAtPoint(new Point(1, 1));
                //listView1.ItemSelectionChanged = ctrl_imglist;

                //Progbar
                progressBar.Visible = true; 
                progressBar.Minimum = 1;
                progressBar.Maximum = images.Length;
                progressBar.Value = 1;
                progressBar.Step = 1;
                
                int i = 0;
                foreach (String img in images)
                {
                    progressBar.Value = (int)Math.Round((i / (double) images.Length)) * 100;
                    upImages.Add(img);
                    Console.Write(img);
                    //bitmap = new Bitmap(img);
                    //newW = 150;
                    //newH = (int) Math.Round((newW / (double) bitmap.Width) * bitmap.Height);
                    //newS = new Size(newW,newH);
                    //tnbitmap = new Bitmap(bitmap, newW, newH);
                    //tnbitmap = bitmap;

                    //pictureBox1.Image = tnbitmap;
                    //Image tmpimag = (Image)tnbitmap;
                    //imageList.Images.Add(tmpimag);
                    //fileFolder.Images.Add(tmpimag);
                    
                    String[] ImgName = {(img.Substring(img.LastIndexOf("\\") + 1)), img};
                    ListViewItem listItem = new ListViewItem(ImgName);//, (fileFolder.Images.Count - 1));
                    
                    listView1.Items.Add(listItem);
                    i++;

                    progressBar.PerformStep();
                }
                listView1.SmallImageList = fileFolder;
                listView1.LargeImageList = null;
                listView1.StateImageList = null;
                //
                /*
                Graphics g = this.CreateGraphics();
                for (int i = 0; i < fileFolder.Images.Count; i++)
                {
                    imageList.Draw(g, 30 + i * 30, 30, i);
                }
                g.Dispose();
                */
            }

            //String[] imageFiles = di.GetFiles(Application.StartupPath, "*.jpg");
            /*
            foreach (String imageFile in imageFiles)
            {
                Bitmap newImage = new Bitmap(imageFile);
                imageList.Images.Add(newImage);
            }*/
        }

        /**
         * EXIF-Kommentar von Bild ändern
         * (damit ohni Qualitätsverlust, umständlich über drehen und zurückdrehen)
         *
         */
        private void changeImageComment(String file, String newComment)
        {
            Image pic;
            Image picn;

            //Bild laden und Comment einfügen
            //byte[] bComment = new Byte[newComment.Length];
            //for (int i = 0; i < newComment.Length; i++) bComment[i] = (byte)newComment[i];
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] bComment = encoding.GetBytes(newComment);


            //Image pic = Image.FromFile(file);
            Console.Write(file);
            pic = Image.FromFile(file);
            
            PropertyItem[] pi = pic.PropertyItems;
            pi[0].Id = 0x9C9C;
            pi[0].Type = 2;
            pi[0].Len = newComment.Length;
            pi[0].Value = bComment;
            pic.SetPropertyItem(pi[0]);

            System.Drawing.Imaging.Encoder Enc = System.Drawing.Imaging.Encoder.Transformation;
            EncoderParameters EncParms = new EncoderParameters(1);
            EncoderParameter EncParm;
            ImageCodecInfo CodecInfo = GetEncoderInfo("image/jpeg"); //pic.GetType()); //

            //90° gedreht speichern
            String tempFile = file.Replace(".", "_temp_");
            EncParm = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate90);
            EncParms.Param[0] = EncParm;
            pic.Save(tempFile, CodecInfo, EncParms); //speichern

            //Speicher freigeben
            pic.Dispose();
            pic = null;
            GC.Collect();

            //System.IO.File.Delete(file); //Original löschen

            //Wieder zurück drehen
            picn = Image.FromFile(tempFile);
            EncParm = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate270);
            EncParms.Param[0] = EncParm;
            picn.Save(file, CodecInfo, EncParms); //überschreiben

            //aufräumen
            picn.Dispose();
            picn = null;
            GC.Collect();
            System.IO.File.Delete(tempFile); 
        }
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            } return null;
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings frmSettings = new Settings();
            frmSettings.ShowDialog();

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "Bilddateien|*.jpg;*.png;*.gif";
            openFileDialog1.Title = "Select the Image Files";

            fileFolder = new ImageList(new System.ComponentModel.Container());

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                String[] images = openFileDialog1.FileNames;
                
                int i = 0;
                foreach (String img in images)
                {
                    progressBar.Value = (int)Math.Round((i / (double)images.Length)) * 100;
                    upImages.Add(img);
                    
                    String[] ImgName = { (img.Substring(img.LastIndexOf("\\") + 1)), img };
                    ListViewItem listItem = new ListViewItem(ImgName);//, (fileFolder.Images.Count - 1));

                    listView1.Items.Add(listItem);
                    i++;
                }
                listView1.View = View.SmallIcon;
                listView1.SmallImageList = fileFolder;
                listView1.LargeImageList = null;
                listView1.StateImageList = null;
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            foreach (ListViewItem s in listView1.SelectedItems)
            {
                upImages.RemoveAt(s.Index);
                listView1.Items[s.Index].Remove();
            }
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem it = listView1.GetItemAt(e.X, e.Y);
            //Image img = fileFolder.Images[it.ImageIndex];
            //Bild anzeigen
            actFile = (String)upImages[it.Index];
            Image img = new Bitmap(actFile);
            int newW = 150;
            int newH = (int)Math.Round((newW / (double)img.Width) * img.Height);
            Size newS = new Size(newW, newH);
            Bitmap newImage = new Bitmap(img, newS);
            pictureBox1.Image = newImage;

            //Kommentar
            Encoding ascii = Encoding.ASCII;
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap((String)upImages[it.Index]);
            Goheer.EXIF.EXIFextractor er = new Goheer.EXIF.EXIFextractor(ref bmp, "\n");
            foreach (System.Web.UI.Pair s in er){
                //Console.Write(s.First+" : " + s.Second +"\n");
            }
            txtExifComment.Text = "";
            if (er["XPComment"] != null)
            {
                txtExifComment.Text = (String)er["XPComment"];
            }
            //er.setTag(0x9C9D, "test von chregi");
            Console.Write("COMMENTS: "+er);
        }


        private void showTreeView(String xml)
        {
            webTree.Nodes.Clear();
            
            // Load the XML Document
            XmlDocument doc = new XmlDocument();
            try
            {
                //doc.Load(xml);
                doc.LoadXml(xml);
            }
            catch (Exception err)
            {
                MessageBox.Show("NO DOC!!!"+err.Message);
                return;
            }

            ConvertXmlNodeToTreeNode(doc, webTree.Nodes);
            webTree.Nodes[0].ExpandAll();

        }

        private void ConvertXmlNodeToTreeNode(XmlNode xmlNode, TreeNodeCollection treeNodes)
        {
            TreeNode newTreeNode = treeNodes.Add("Typo3");
                    
            switch (xmlNode.NodeType)
            {
                case XmlNodeType.ProcessingInstruction:
                case XmlNodeType.XmlDeclaration:
                    //newTreeNode.Text = "<?" + xmlNode.Name + " " +xmlNode.Value + "?>";
                    break;
                case XmlNodeType.Element:
                    newTreeNode.Text = "" + xmlNode.Name + "";
                    break;
                case XmlNodeType.Attribute:
                    //newTreeNode.Text = "ATTRIBUTE: " + xmlNode.Name;
                    break;
                case XmlNodeType.Text:
                case XmlNodeType.CDATA:
                    //newTreeNode.Text = xmlNode.Value;
                    break;
                case XmlNodeType.Comment:
                   // newTreeNode.Text = "<!--" + xmlNode.Value + "-->";
                    break;
            }

            /*if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attribute in xmlNode.Attributes)
                {
                    ConvertXmlNodeToTreeNode(attribute, newTreeNode.Nodes);
                }
            }*/
            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                ConvertXmlNodeToTreeNode(childNode, newTreeNode.Nodes);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            /* string sUrl = "http://www.agentur-frontal.ch/DATA/team.xml";
            StringBuilder oBuilder = new StringBuilder();
            StringWriter oStringWriter = new StringWriter(oBuilder);
            XmlTextReader oXmlReader = new XmlTextReader(sUrl);
            XmlTextWriter oXmlWriter = new XmlTextWriter(oStringWriter);
            while (oXmlReader.Read())
            {
                oXmlWriter.WriteNode(oXmlReader, true);
            }
            oXmlReader.Close();
            oXmlWriter.Close();
            Console.WriteLine(oBuilder.ToString()); 
            */
            // parameters: name1=value1&name2=value2	
            WebRequest webRequest = WebRequest.Create("http://www.pfadiwillisau.ch/imgupp.php");
            //string ProxyString = 
            //   System.Configuration.ConfigurationManager.AppSettings
            //   [GetConfigKey("proxy")];
            //webRequest.Proxy = new WebProxy (ProxyString, true);
            //Commenting out above required change to App.Config
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            String parameter = "login=admin&kennwort=2ymsek";
            byte[] bytes = Encoding.ASCII.GetBytes(parameter);
            Stream os = null;
            try
            { // send the Post
                webRequest.ContentLength = bytes.Length;   //Count bytes to send
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         //Send it
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message, "HttpPost: Request error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            try
            { // get the response
                WebResponse webResponse = webRequest.GetResponse();
                if (webResponse == null)
                {
                    //return null; 
                }
                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                //return sr.ReadToEnd().Trim();
                String Response = sr.ReadToEnd().Trim();
                showTreeView(Response);
                Console.WriteLine(Response);
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message, "HttpPost: Response error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //return null;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TreeNode actNode = webTree.SelectedNode;
            String path = "/"+actNode.Text;
            
            while(actNode.Parent!=null){
                path = "/" + actNode.Parent.Text + path;
                actNode = actNode.Parent;
            }
            lblT3Path.Text = path;
            Properties.Settings.Default.set_path = path;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Settings frmSet = new Settings();
            frmSet.ShowDialog();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //Ein Request erstellen an den ftp Server
            Uri rqu = new Uri("ftp://ftp.pfadiwillisau.ch/");

            //Alle Files hochladen
            foreach (String img in upImages)
            {
                String filename = img.Substring(img.LastIndexOf("\\"));
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.pfadiwillisau.ch/"+filename);

                //Die Methode angeben um eine Datei hochzuladen
                request.Method = WebRequestMethods.Ftp.UploadFile;

                //Berechtigungsdetails setzen vom ftp Server durch Username und Passwort
                request.Credentials = new NetworkCredential("pfadiw", "as1z5g");

                try
                {
                    //Versuch eine Verbindung zu erstellen und eine Antwort zu erhalten
                    WebResponse response = request.GetResponse();
                    MessageBox.Show("Response hat funktioniert: " + response.ToString());
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }


            
                FileStream fs = new FileStream(img, FileMode.Open);
                byte[] fileContents = new byte[fs.Length];
                fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));
                fs.Flush();
                fs.Close();
                
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();


                //Verbindung abbschliessen
                request.Abort();  
            }

            
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //Bild freigeben, (damit überschreibbar)
            String newComment = txtExifComment.Text;
            pictureBox1.Image.Dispose();
            txtExifComment.Text = "";

            //Kommentar speichern
            changeImageComment(this.actFile, newComment);
        }



    }
}
